<template>
    <div class="miniProgram">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :row-key="getRowKey"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button type="primary" @click="addMiniApp">新增小程序素材</el-button>
            </template>
        </ZwTable>
    </div>
    <Dialog :app-dialog="appDialog">
        <el-form ref="minRef" :model="minForm" label-width="120px" :rules="miniRules">
            <el-form-item label="小程序AppID" prop="appid">
                <el-input v-model.trim="minForm.appid" placeholder="请输入小程序AppID" />
            </el-form-item>
            <el-form-item>
                <div class="mini_box">
                    <p class="title">注意</p>
                    <p>
                        1、请先在企业微信的后台应用中关联此小程序的应用。
                        <span class="how" @click="howApp"> 如何关联？</span>
                    </p>
                    <p>
                        2、请确保添加同一主体、同一开放平台的小程序，如果主体不一致，可能会导致小程序进来的客户数据无法跟系统客户匹配。
                    </p>
                </div>
            </el-form-item>
            <el-form-item label="素材标题" prop="title">
                <el-input v-model="minForm.title" placeholder="请输入素材标题" />
            </el-form-item>
            <el-form-item label="页面地址" prop="path">
                <el-input v-model="minForm.path" placeholder="请输入小程序页面地址。例如：Page/Index.html" />
            </el-form-item>
            <el-form-item label="分享封面" prop="code">
                <ZWUpload ref="emptyData" :up-info="picInfo" @submit="getFileList" />
            </el-form-item>
        </el-form>
    </Dialog>
</template>

<script lang="tsx" setup>
import { ref, reactive, computed, nextTick } from 'vue';
import { ElMessage, ElImage, ElIcon, ElButton, ElMessageBox } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';

import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import Dialog from '@/components/Dialog.vue';
import ZWUpload from '@/components/ZWUpload.vue';
import { miniProgram, createMiniApp, delMiniApp, lookConfig, editMini } from '@/api/content/channelFootage/miniProgram';

import { deepCopy } from '@/utils/helper';

const tableRef = ref();
const minRef = ref();
const emptyData = ref();
const isEdit = ref(false);
const minForm = reactive({
    title: '',
    appid: '',
    code: '',
    path: ''
});

const defaultParams = reactive({
    title: '',
    appid: ''
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
/**
 * @description: 自定义校验 标题字节数
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 * @return {*}
 */
const validateTitle = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请输入素材标题'));
    } else {
        const blob = new Blob([value], {
            type: 'text/plain'
        });
        if (blob.size > 64) {
            callback(new Error('素材标题不超过20个汉字或最多64个英文字母'));
        } else {
            callback();
        }
    }
};
const miniRules = reactive({
    appid: [{ required: true, message: '请输入小程序AppID', trigger: 'blur' }],
    title: [
        { required: true, message: '请输入素材标题', trigger: 'blur' },
        { validator: validateTitle, trigger: 'blur' }
    ],
    code: [{ required: true, message: '请上传分享封面', trigger: 'blur' }],
    path: [{ required: true, message: '请输入小程序页面地址。例如：Page/Index.html', trigger: 'blur' }]
});
const searchOption = computed(() => {
    return [
        {
            label: '素材标题',
            name: 'title',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '输入素材标题进行搜索'
        },
        {
            label: '小程序AppID',
            name: 'appid',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '输入小程序AppID进行搜索'
        }
    ];
});
const tableOption = computed(() => [
    {
        prop: 'title',
        label: '素材标题'
    },
    {
        prop: 'appid',
        label: '小程序AppID',
        render({ row }) {
            return <span>{row.appid || '--'}</span>;
        }
    },
    {
        label: '封面',
        render({ row, column, index }) {
            const slotError = () => (
                <div class="image_slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <div class="imgInfo">
                    <ElImage
                        preview-src-list={[row.image_url]}
                        preview-teleported={true}
                        vSlots={{ error: slotError }}
                        src={row.image_url}
                        fit="cover"
                        class="avatar"></ElImage>
                </div>
            );
        }
    },
    {
        prop: 'path',
        label: '页面地址',
        render({ row }) {
            return <span>{row.path || '--'}</span>;
        }
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 260,
        isOperate: true,
        renderOperate({ row, column, index }) {
            return (
                <div class="handle">
                    <ElButton size="small" onClick={() => edit(row)}>
                        编辑
                    </ElButton>
                    <ElButton size="small" onClick={() => del(row)}>
                        删除
                    </ElButton>
                </div>
            );
        }
    }
]);
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return miniProgram;
};
const getRowKey = (row: any) => {
    return row.id;
};
const search = (data: any) => {
    state.searchParams = deepCopy(data);
};
const reset = (v?: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy(v);
};
const getTableH = () => {
    nextTick(() => {});
};
const cancelHandel = (isReload = 0, tip?: string) => {
    if (!minRef.value) return;
    minRef.value.resetFields();
    if (isReload > 0) {
        ElMessage.success(tip);
        tableRef.value.reload();
    }
    appDialog.visible = false;
};
/**
 * @description: 新增或编辑 确定提交
 * @return {*}
 */
const submitHandel = async () => {
    if (!minRef.value) return;
    minRef.value.validate((valid: any, fields: any) => {
        if (valid) {
            minForm.appid = minForm.appid.trim(); // 保存时同时也清除掉两端的空格
            if (!isEdit.value) {
                createMiniApp(minForm).then((res: any) => {
                    cancelHandel(1, '创建成功！');
                });
            } else {
                editMini(minForm).then((res: any) => {
                    cancelHandel(1, '编辑成功！');
                });
            }
        }
    });
};
const edit = (row: any) => {
    appDialog.title = '编辑小程序素材';
    appDialog.visible = true;
    lookConfig({ id: row.id }).then(async (res: any) => {
        isEdit.value = true;
        Object.assign(minForm, res);
        // bus.emit('echo', [{ absolute_url: res.image_url, code: res.code }])
        emptyData.value.echo([{ type: 1, url: res.image_url, code: res.code }], true);
    });
};
const addMiniApp = () => {
    isEdit.value = false;
    appDialog.title = '新增小程序素材';
    appDialog.visible = true;
};
const getFileList = (data: any) => {
    minForm.code = data?.[0]?.code;
};
const del = (row: any) => {
    ElMessageBox.alert('确定删除所选内容吗？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        delMiniApp({ id: [row.id] }).then(() => {
            ElMessage({
                type: 'success',
                message: '删除成功'
            });
            tableRef.value.reload();
        });
    });
};
const howApp = () => {
    window.open('/associated-applet');
};

const picInfo = reactive({
    type: 1,
    label: '',
    prop: 'images',
    files: minForm.code,
    multiple: true,
    limitSize: 20,
    limitNum: 1,
    acceptFile: '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG',
    limitSizeCover: '图片支持JPG、PNG、JPEG格式，大小2M以内，建议宽高比为5：4，尺寸520px*416px'
});
const appDialog = reactive({
    visible: false,
    title: '新增小程序素材',
    width: '610px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});
</script>

<style lang="scss" scoped>
.miniProgram {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    :deep(.imgInfo) {
        width: 30px;
        height: 30px;
    }
}

:deep(.el-form-item) {
    margin-bottom: 17px;
}

.mini_box {
    background: #fffaf9;
    border-radius: 4px;
    font-size: 14px;
    padding: 16px;

    p {
        line-height: 20px;
    }

    .title {
        color: #ff6b00;
    }

    .how {
        color: #ff6b00;
        cursor: pointer;
    }
}
</style>
